import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, TextInput, ImageBackground, ActivityIndicator } from 'react-native';
import SearchInput from './components/SearchInput';
import getImageForWeather from './utils/getImageForWeather'
import { fetchLocationId, fetchWeather } from './utils/api'


export default class App extends React.Component {
  state = {
    location: 'Chengdu',
    weather: "Heavy Rain",
    temperature: "15.7",
    loading: true
  }

  componentDidMount = () => {
    //默认值成都
    this.handleUpdateLocation("chengdu")
  }

  handleUpdateLocation = async city => {
    // 判断用户是否有输入
    if (!city)
      return;

    console.log("第一次loading============>" + this.state.loading)
    
    this.setState(
      {
        loading: true
      },
      async () => {
        const locationId = await fetchLocationId(city);
        const { location, weather, temperature } = await fetchWeather(locationId);

        console.log(location, weather, temperature)

        this.setState({
          location,
          weather,
          temperature,
          loading: false
        });
        console.log("第二次loading============>" + this.state.loading)

      });

  }

  normalView() {
    let { location, weather, temperature, loading } = this.state
    console.log(location)
    console.log(weather)
    console.log(temperature)

    if (loading) {
      return (
        <ActivityIndicator size="large" color="#00ff00" />
      )
    } else {
      return (
        <View>
          <Text style={styles.largeText}>{location}</Text>
          <Text style={styles.smallText}>{weather}</Text>
          <Text style={styles.largeText}>{temperature}</Text>
        </View>

      );
    }

  }


  render() {
    const { location, weather, temperature, loading } = this.state

    return (

      <View style={styles.container}>
        <StatusBar style="auto" />
        <ImageBackground
          source={getImageForWeather(weather)}
          style={styles.imageContainer}
          imageStyle={styles.image} >
          <View style={styles.contentContainer}>
            {this.normalView()}
            <SearchInput
              placeholder="请输入城市"
              onSubmit={this.handleUpdateLocation} />
          </View>
        </ImageBackground>
      </View>


    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },

  contentContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 20
  },

  imageContainer: {
    flex: 1,
  },
  image: {
    flex: 1,
    width: null,
    height: null,
    resizeMode: 'cover'
  },

  largeText: {
    fontSize: 56
  },
  smallText: {
    fontSize: 22
  }
});
